import { getToken } from '@/utils/auth';
import useNoticeStore from '@/store/modules/notice';
import { h, ref, watch } from 'vue';
import { ElNotification } from 'element-plus';
import { useEventSource } from '@vueuse/core';

// 初始化
export const initSSE = (url: any) => {
  if (import.meta.env.VITE_APP_SSE === 'false') {
    return;
  }

  url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
  const { data, error } = useEventSource(url, [], {
    autoReconnect: {
      retries: 10,
      delay: 3000,
      onFailed() {
        console.log('Failed to connect after 10 retries');
      }
    }
  });

  const dialogVisible = ref(false);
  const employeeTaskInfo = ref<
    {
      employeeName: string;
      historyExceedTaskList: string[];
      todayUnFinishedTaskList: string[];
      unauditedTaskList: string[];
      waitingForMyApprovalTaskList: string[];
    }[]
  >([]);

  watch(error, () => {
    console.log('SSE connection error:', error.value);
    error.value = null;
  });

  watch(data, () => {
    if (!data.value) return;
    if (data.value.includes('employeeName')) {
      // 解析 JSON 字符串
      const parsedData = JSON.parse(data.value);

      // 处理可能缺失的属性
      // 更新 employeeTaskInfo
      employeeTaskInfo.value = parsedData.map((item) => ({
        employeeName: item.employeeName,
        historyExceedTaskList: item.historyExceedTaskList || [],
        todayUnFinishedTaskList: item.todayUnFinishedTaskList || [],
        unauditedTaskList: item.unauditedTaskList || [],
        waitingForMyApprovalTaskList: item.waitingForMyApprovalTaskList || []
      }));

      showEmployeeNotification();
    } else {
      // 处理普通消息
      useNoticeStore().addNotice({
        message: data.value,
        read: false,
        time: new Date().toLocaleString()
      });

      // 模拟消息数据
      const messageData = [
        {
          content: data.value,
          time: new Date().toLocaleString()
        }
      ];

      ElNotification({
        title: '新消息通知',
        position: 'bottom-right',
        duration: 0,
        customClass: 'custom-notification',
        message: h('div', { class: 'message-list' }, [
          ...messageData.map((item) =>
            h(
              'div',
              {
                class: 'message-item',
                onClick: () => handleMessageClick(item),
                style: 'cursor: pointer; transition: background 0.3s'
              },
              [
                h('span', { class: 'message-time' }, item.time + '：'),
                h('span', { class: 'message-content' }, item.content)
                // h('span', { class: 'changeToRead'}, '标记为已读')
              ]
            )
          )
        ])
      });

      data.value = null;
    }
  });

  const showEmployeeNotification = () => {
    // 获取响应式对象的值
    let employeeData = employeeTaskInfo.value;
    // 强制转换为数组
    if (!Array.isArray(employeeData)) {
      employeeData = [employeeData];
    }

    // 检查 employeeData 是否为空
    if (employeeData.length === 0) {
      console.log('员工数据为空，不显示通知');
      return;
    }

    // 简化 message 内容进行测试
    const simpleMessage = h('span', '这是一个简单的测试消息');

    // 生成复杂的 message 内容
    const complexMessage = h(
      'div',
      { class: 'employee-task-progress' },
      employeeData.map((employee) => {
        return h('div', { class: 'employee-box', key: employee.employeeName }, [
          h('p', employee.employeeName),
          h('p', { class: 'task-label' }, '历史超期任务列表:'),
          employee.historyExceedTaskList.length > 0
            ? h(
                'ul',
                employee.historyExceedTaskList.map((task) => h('li', { class: 'exceed-task-item' }, task))
              )
            : h('p', '无'),
          h('p', { class: 'task-label' }, '今日未完成任务列表:'),
          employee.todayUnFinishedTaskList.length > 0
            ? h(
                'ul',
                employee.todayUnFinishedTaskList.map((task) => h('li', task))
              )
            : h('p', '无'),
          h('p', { class: 'task-label' }, '未审核任务列表:'),
          employee.unauditedTaskList.length > 0
            ? h(
                'ul',
                employee.unauditedTaskList.map((task) => h('li', task))
              )
            : h('p', '无'),
          h('p', { class: 'task-label' }, '待我审批任务列表:'),
          employee.waitingForMyApprovalTaskList.length > 0
            ? h(
                'ul',
                employee.waitingForMyApprovalTaskList.map((task) => h('li', task))
              )
            : h('p', '无')
          // h(ElProgress, { percentage: employee.progress })
        ]);
      })
    );

    ElNotification({
      title: '今日员工任务完成信息',
      position: 'bottom-left',
      // width: '1200px',
      // height: '1200px',
      customClass: 'custom-employee-notification',
      duration: 0,
      message: complexMessage
      // message: h(
      //   'div',
      //   { class: 'employee-task-progress' },
      //
      //   // employeeData.map((employee) =>
      //   //   h('div', { class: 'employee-box', key: employee.employeeName }, [
      //   //     h('p', employee.employeeName)
      //   //     // h(ElProgress, { percentage: employee.progress })
      //   //   ])
      //   // )
      //   employeeData.map((employee) => {
      //     console.log('当前员工数据:', employee);
      //     return h('div', { class: 'employee-box', key: employee.employeeName }, [
      //       h('p', employee.employeeName)
      //       // h(ElProgress, { percentage: employee.progress })
      //     ]);
      //   })
      // )
    });
  };

  return {
    dialogVisible,
    employeeTaskInfo
  };
};

// 添加消息点击处理函数
const handleMessageClick = (item: any) => {
  console.log('点击的消息数据:', item);
  // return request({
  //   url: '/userMessage/userMessage/changeToRead',
  //   method: 'post',
  //   data: {
  //     messageTitle: item.content
  //   }
  // });
};
